package com.pro.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import com.pro.entity.UserEntity;
import com.pro.util.DBManager;
import com.pro.util.DateUtil;
import com.pro.util.QueryResult;

public class UserDaoImpl {
	public UserEntity login(String name) {
		UserEntity userEntity = null;
		String sqlString = "select id,create_time,name,pwd from user where name = '"+name+"'";
		QueryResult result = DBManager.executeQuery(sqlString);
		if(result!=null) {
			try {
				while(result.rs.next()) {
					userEntity = new UserEntity(
							result.rs.getInt("id"), 
							result.rs.getDate("create_time"),
							result.rs.getString("name"),
							result.rs.getString("pwd"));
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		result.close();
		return userEntity;
	}
	
	public ArrayList<UserEntity> user(){
		ArrayList<UserEntity> alist= new ArrayList<UserEntity>();
		String sqlString="select id,create_time,name,pwd from user";
	    QueryResult rSet=DBManager.executeQuery(sqlString);
	      if (rSet!=null) {
	        try {
	          while (rSet.rs.next()) {
	        	  alist.add(new UserEntity(rSet.rs.getInt("id"),
	            		rSet.rs.getDate("create_time"),
	            		rSet.rs.getString("name"),
	            		rSet.rs.getString("pwd")));
	          }
	        } catch (SQLException e) {
	          e.printStackTrace();
	        }
	      }
	      rSet.close();
	    return alist;
	}
	
	public int userAdd(UserEntity uEntity) {
 		String sqlString="insert into user(create_time,name,pwd) values('"+DateUtil.DateToDate(new Date())+"'"
 				+ ",'"+uEntity.getName()+"'"
 				+ ",'"+uEntity.getPwd()+"')";
 		 int result= DBManager.executeUpdate(sqlString);
 		return result;
 	}
	
	 public int userUpdate(UserEntity uEntity) {
	 		String sqlString="update user set create_time='"+DateUtil.DateToDate(new Date())+"',name='"+uEntity.getName()+"',pwd='"+uEntity.getPwd()+"' where id = '"+uEntity.getId()+"'";
	 		 int result= DBManager.executeUpdate(sqlString);
	 		return result;
	 	}
	 
	 public int userDelete(int id) {
			// TODO Auto-generated method stub
			String sqlString = "delete from user where id = '"+id+"'";
			int result = DBManager.executeUpdate(sqlString);
			return result;
		}
	
}
